package com.xpalive.attach.controller;

import com.xpalive.commons.LogPool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.slf4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/attach")
@Api(
    tags = {"attach"}
)
public class AttachmentController {

    private final Logger log = LogPool.LOGGER_BIZ;

    @GetMapping("/download")
    @ApiOperation("文件下载")
    public ResponseEntity<byte[]> download() throws UnsupportedEncodingException {
        HttpHeaders headers = new HttpHeaders();
        String fileName = "熊平.txt";
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String nameISO = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        headers.setContentDispositionFormData("attachment", nameISO);
        headers.set("x-suggested-filename", URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));
        headers.setAccessControlExposeHeaders(
            Arrays.asList("Content-Disposition", "x-suggested-filename"));
        byte[] content = fileName.getBytes(StandardCharsets.UTF_8);
        return new ResponseEntity<>(content, headers, HttpStatus.OK);
    }

    @PostMapping("/upload")
    @ApiOperation("文件下载")
    public Boolean upload(@RequestParam(value = "file") MultipartFile file) {
        log.info(file.getOriginalFilename());
        return true;
    }
}
